package gui.display;

import java.util.Collections;
import java.util.LinkedList;
import javax.swing.BoxLayout;
import javax.swing.JPanel;

/**
 * 
 */
public class ChannelUsersPanel extends JPanel
{
    private final ChatDisplay display_;
    private final LinkedList<ChannelUser> users_ = new LinkedList<ChannelUser>();
    
    public ChannelUsersPanel( final ChatDisplay display )
    {
        super();
        display_ = display;
        setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) );
    }

    public final void addUsers( final String users )
    {
        int index = -1;
        String rest = users;
        users_.clear();
        while( true )
        {
            index = rest.indexOf( " " );
            if( index == -1 )
            {
                addUser( rest );
                break;
            }
            else
                //addUser( rest.substring( 0, index ) );
                users_.add( new ChannelUser( rest.substring( 0, index ) ) );
            rest = rest.substring( index + 1 );
        }

        sortUsers();
        addUsersToPanel();
    }

    private void sortUsers()
    {
        Collections.sort( users_ );
    }

    private void addUsersToPanel()
    {
        reset();
        for( ChannelUser user : users_ )
            add( user );

        validate();
        repaint();
    }

    private void addUser( final String user )
    {
        // Add ChannelUser with the name and mode
        add( new ChannelUser( user ) );
    }

    public final void handleNick( final String oldNick, final String newNick )
    {
        // Find the user
        // Change its name
    }

    public final void handleJoin( final String nick )
    {
        users_.add( new ChannelUser( nick ) );
        sortUsers();
        addUsersToPanel();
    }

    public final void handlePartQuit( final String nick )
    {
        for( ChannelUser u : users_ )
            if( u.getNick().equalsIgnoreCase( nick ) )
            {
                users_.remove( u );
                addUsersToPanel();
                return;
            }
        System.out.println( "handlePartQuit: No user with nick: " + nick );
    }

    /*public final void handleModes( final String mode )
    {
        // Find the user
        // Change its mode
    }*/

    void reset()
    {
        removeAll();
        validate();
    }
}
